<template>
  <div class="ccui-home-index">
    <div class="ccui-app-container">
      <!-- 高级搜索 -->
      <div class="ccui-advanced-search-wrapper ccui-clearfix">
        <el-search
          ref="search"
          :formProp="formData"
          @search="search"
          @change="change"
          :isShowSearch="true"
          :selectClear="true"
          class="ccui-highsearch no-print"
        >
          <anchorTitle
            isList
            :totalNum="totalNum"
            :tabBtn="tableTopBtn"
            :isFocus="isFocus"
            @tabBtnChange="tableTopChange"
          />
          <template slot="search">
            <el-input
              v-model.trim="formData.contractName"
              clearable
              searchLabel="合同名称"
              placeholder="请输入合同名称模糊查询"
            ></el-input>

            <el-input
              v-model.trim="formData.contractCode"
              clearable
              searchLabel="合同编号"
              placeholder="请输入合同编号模糊查询"
            ></el-input>

            <el-input
              v-model.trim="formData.partyBName"
              clearable
              searchLabel="供应商1"
              placeholder="请输入供应商1名称模糊查询"
            ></el-input>

            <el-input
              v-model.trim="formData.partyBNameBak"
              clearable
              searchLabel="供应商2"
              placeholder="请输入供应商2名称模糊查询"
            ></el-input>

            <el-input
              v-model.trim="formData.reportInOrgName"
              clearable
              searchLabel="填报单位"
              placeholder="请输入填报单位模糊查询"
            ></el-input>

            <el-date-picker
              v-model="formData.compileDate"
              slot="searchItem3"
              searchLabel="编制日期"
              clearable
              type="date"
              placeholder="请选择编制日期查询"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />

            <el-input
              v-model.trim="formData.partyAName"
              clearable
              searchLabel="合同签订单位(甲方)"
              placeholder="请输入合同签订单位(甲方)模糊查询"
            ></el-input>

            <el-input
              v-model.trim="formData.thirdCategoriesOfName"
              clearable
              searchLabel="分类名称"
              placeholder="请输入分类名称模糊查询"
            ></el-input>

            <el-select
              class="ccui-form-longInput"
              v-model="formData.searchState"
              searchLabel="合同状态"
              placeholder="请选择合同状态查询"
              clearable
            >
              <el-option
                v-for="item in jsList.contractState"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
          <el-input
            v-model.trim="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
            slot="searchItem2"
          ></el-input>

          <el-input
            v-model.trim="formData.contractCode"
            clearable
            searchLabel="合同编号"
            placeholder="请输入合同编号模糊查询"
            slot="searchItem1"
          ></el-input>

          <el-input
            v-model.trim="formData.partyBName"
            clearable
            searchLabel="供应商1"
            placeholder="请输入供应商1名称模糊查询"
            slot="searchItem3"
          ></el-input>

          <el-input
            v-model.trim="formData.partyBNameBak"
            clearable
            searchLabel="供应商2"
            placeholder="请输入供应商2名称模糊查询"
            slot="searchItem4"
          ></el-input>

          <el-input
            v-model.trim="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
            slot="searchItem5"
          ></el-input>

          <el-date-picker
            v-model="formData.compileDate"
            slot="searchItem6"
            searchLabel="编制日期"
            clearable
            type="date"
            placeholder="请选择编制日期查询"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />

          <el-input
            v-model.trim="formData.partyAName"
            clearable
            searchLabel="合同签订单位(甲方)"
            placeholder="请输入合同签订单位(甲方)模糊查询"
            slot="searchItem7"
          ></el-input>

          <el-input
            v-model.trim="formData.thirdCategoriesOfName"
            clearable
            searchLabel="分类名称"
            placeholder="请输入分类名称模糊查询"
            slot="searchItem8"
          ></el-input>

          <el-select
            class="ccui-form-longInput"
            v-model="formData.searchState"
            searchLabel="合同状态"
            placeholder="请选择合同状态查询"
            slot="searchItem9"
            clearable
          >
            <el-option
              v-for="item in jsList.contractState"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-search>
      </div>
      <!-- table表格 -->
      <div class="ccui-multifunctional-table-wrapper">
        <el-table
          :data="tableData"
          :fit="true"
          :cell-style="cellStyle"
          border
          class="ccui-multifunctional-table"
          @header-dragend="tableTitleWidth"
          @row-click="handleRowClick"
        >
          <el-table-column label="序号" width="50" fixed>
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>

          <template v-for="(table, index) in tableTheadOptions">
            <el-table-column
              :fixed="table.fixed || false"
              :key="index"
              :type="table.type"
              :label="table.label"
              :min-width="table.width"
              :prop="table.prop"
              :align="table.align || 'left'"
              :header-align="table.headerAlign || 'left'"
              :filters="table.filters"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </template>

          <el-table-column label="操作" width="50" fixed="right">
            <template slot-scope="{ row }">
              <el-button
                v-if="!row.recordId && ['5'].includes(row.contractState)"
                size="mini"
                type="text"
                @click="setTakeEffect(row)"
                >生效</el-button
              >
              <el-button
                v-if="row.recordId && !['9'].includes(row.contractState)"
                size="mini"
                type="text"
                @click="editTakeEffect(row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="ccui-table-footer" v-show="tableData.length > 0">
          <div id="ccui-paging">
            <el-pagination
              :total="totalNum"
              :page-size="pageSizeCode"
              :current-page="pageNoCode"
              :page-sizes="[10, 20, 50, 100, 200, 500]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              popper-class="ccui-paging-page-size-popper"
              @prev-click="handlePrev"
              @next-click="handleNext"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-button
              class="ccui-pagination-btn"
              size="mini"
              type="default"
              @click="handleSizeChange('none')"
              >确定</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import jsList from "../js";
import baseJsObj from "@/app/contractManagement/equipmentContract/contractDraft/js";
import anchorTitle from "@/basa/components/public/anchorTitle";
import { setSessionItem, getSessionItem, proxyDateFormat } from "@/basa/utils";
import { getList } from "../api";

export default {
  components: {
    anchorTitle
  },
  data() {
    return {
      jsList,
      baseJsObj,
      formData: {
        contractName: "",
        contractCode: "",
        partyBName: "",
        partyBNameBak: "",
        reportInOrgName: "",
        compileDate: "",
        partyAName: "",
        thirdCategoriesOfName: "",
        searchState: ""
      },
      draggFlag: true,
      tableName: this.tableList.eqContractTakeEffectList, // 表格命名
      // 动态表格
      tableTheadOptions: [],
      // 全选以及页码
      totalNum: 0,
      total: 0,
      pageNoCode: 1,
      pageSizeCode: 10,
      formDataSearch: {},
      localSearchData: {},
      tableData: [{ subContractName: "F123", id: 1 }],
      // 表格顶部按钮
      tableTopBtn: [
        { label: "全部", value: "1" },
        { label: "待生效", value: "5" },
        { label: "已生效", value: "9" }
      ],
      isFocus: "1",
      contractState: "1"
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.setTableWidth();
      this.renderTable();
    },

    // 列表数据请求
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.contractState = this.contractState;
      obj.reportOrgId = getSessionItem("userInfo", "orgId");
      getList(obj)
        .then(res => {
          if (res.data.data.rows.length) {
            this.tableData = res.data.data.rows.map(n => ({
              ...n,
              // 编制日期
              compileDateStr: n.compileDate
                ? proxyDateFormat(n.compileDate)
                : "",
              // 合同状态
              contractStateStr: jsList.contractState.find(
                _ => _.value === n.contractState
              ).label,
              // 合同金额（含税）
              initTotalContractPriceIncludeTax: Number(
                n.initTotalContractPriceIncludeTax
              ).toFixed(2)
            }));
          } else {
            this.tableData = [];
          }
          this.totalNum = res.data.data.recordsTotal;
          this.total = res.data.data.recordsTotal;
          this.pageNoCode = res.data.data.pageNo;
        })
        .catch(err => {});
    },

    // 生效
    setTakeEffect({ id, recordId }) {
      this.$router.push({
        path: `/contractManagement/equipmentContractTakeEffect/item-add`,
        query: { id, recordId }
      });
    },

    // 编辑
    editTakeEffect({ id, recordId }) {
      this.$router.push({
        path: `/contractManagement/equipmentContractTakeEffect/item-edit`,
        query: { id, recordId }
      });
    },

    // 详情
    goDetail({ id, recordId }) {
      this.$router.push({
        path: `/contractManagement/equipmentContractTakeEffect/item-detail`,
        query: { id, recordId }
      });
    },

    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (["contractCode"].includes(column.property)) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },

    // 行点击事件
    handleRowClick(row, column, event) {
      if (["contractCode"].includes(column.property)) {
        this.goDetail(row);
      }
    },

    // 顶部按钮切换
    tableTopChange({ value }) {
      this.isFocus = value;
      this.contractState = value;
      this.resetFormData();
      this.getList();
    },

    // 重置表单
    resetFormData() {
      this.formData = {
        contractName: "",
        contractCode: "",
        partyBName: "",
        partyBNameBak: "",
        reportInOrgName: "",
        compileDate: "",
        partyAName: "",
        thirdCategoriesOfName: "",
        searchState: ""
      };
      setSessionItem("pageNo", this.tableName, {
        pageNo: 1,
        searchForm: {}
      });
      this.formDataSearch = {};
      this.pageNoCode = 1;
      this.pageSizeCode = 10;
    },

    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.baseJsObj.unfixedTableThead.concat(
        this.baseJsObj.fixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, width, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          this.baseJsObj.unfixedTableThead = localTableData.filter(item => {
            return !this.baseJsObj.fixedTableThead.find(
              cItem => item.prop === cItem.prop
            );
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.baseJsObj.unfixedTableThead.concat(
            this.baseJsObj.fixedTableThead
          );
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.baseJsObj.unfixedTableThead.concat(
          this.baseJsObj.fixedTableThead
        );
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.baseJsObj.unfixedTableThead.length; i++) {
        if (this.baseJsObj.unfixedTableThead[i].label === column.label) {
          this.baseJsObj.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.baseJsObj.unfixedTableThead.concat(
        this.baseJsObj.fixedTableThead
      );
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    // 上一页
    handlePrev() {
      --this.pageNoCode;
      this.getList();
    },
    // 下一页
    handleNext() {
      ++this.pageNoCode;
      this.getList();
    },
    // Todo 高级搜索所需函数 start
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = searchData;
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    }
  },
  activated() {
    this.pageSizeCode = 10;
    this.$refs.search.resetForm();
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    // let localData = getSessionItem(
    //   "pageNo",
    //   this.tableList.eqContractTakeEffectList
    // );
    // let data = localData && localData.searchForm;
    // this.getList({ ...this.formDataSearch, ...data });
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (!/-add|-edit|-detail/g.test(from.path)) {
        vm.isFocus = "1";
        vm.contractState = "1";
      }
      vm.search({});
    });
  }
};
</script>

<style lang="scss" scoped>
/deep/.ccui-advanced-search-wrapper
  .el-search
  .el-searchs-bottom
  .el-form-item
  .el-form-item__label {
  min-width: 126px !important;
}
/deep/.ccui-multifunctional-table {
  .el-table__fixed-right,
  .el-table__fixed {
    height: 100% !important;
  }
}
.ccui-home-index .ccui-statistics-card {
  padding: 0;
}
/deep/.ccui-advanced-search-wrapper
  .el-search
  .ccui-search-wrapper
  .el-searchs
  .el-searchs-right
  .el-input__inner {
  padding: 0px 7px 0 0;
}
</style>
